package utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMqUtils {
    private static final ConnectionFactory factory;

    static {
        // 创建工厂
        factory = new ConnectionFactory();
        // 设置参数
        factory.setHost("192.168.169.130");
        // 设置端口
        factory.setPort(5672);
        // 设置虚拟主机
        factory.setVirtualHost("/echo");
        // 设置用户名
        factory.setUsername("admin");
        // 设置密码
        factory.setPassword("admin");
    }

    // 获取连接对象
    public static Connection getConnection() {
        try {
            return factory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }


    //  关闭通道和连接
    public static void close(Channel channel,Connection connection){
        if(channel != null ){
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }

        if(connection != null ){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
